package com.xzy.controller.d;

import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * 说明：文件上传下载
 *
 * @author xzy
 * @date 2021/11/14 22:20
 */
@Slf4j
@RestController("controllerD")
@RequestMapping("/test_d")
public class TestController {

    /**
     * 文件下载
     */
    @GetMapping("/download")
    public ResponseEntity<byte[]> download(HttpSession session) throws IOException {
        ClassPathResource classPathResource = new ClassPathResource("helloworld.jpg");
        File file = classPathResource.getFile();
        try (FileInputStream fileInputStream = new FileInputStream(file)) {
            // 读取文件至字节数组
            byte[] fileBytes = new byte[fileInputStream.available()];
            fileInputStream.read(fileBytes);

            // 创建HttpHeaders对象设置响应头信息——下载方式以及下载文件的名字
            MultiValueMap<String, String> headers = new HttpHeaders();
            headers.add("Content-Disposition", "attachment;filename=helloworld.jpg");

            return new ResponseEntity<>(fileBytes, headers, HttpStatus.OK);
        }

    }
}
